<template>
  <div id="PictureDetailPage">
    <a-row :gutter="[16, 16]">
      <a-col :sm="24" :xl="18">
        <a-card title="图片预览">
          <a-image style="max-height: 600px; object-fit: cover" :src="picture.url"></a-image>
        </a-card>
      </a-col>
      <a-col :sm="24" :xl="6" :md="8">
        <a-card title="图片信息">
          <a-descriptions :column="1">
            <a-descriptions-item label="作者">
              <a-space>
                <a-avatar :size="24" :src="picture.user?.userAvatar" />
                <div>{{ picture.user?.userName }}</div>
              </a-space>
            </a-descriptions-item>
            <a-descriptions-item label="名称">
              {{ picture.name ?? '未命名' }}
            </a-descriptions-item>
            <a-descriptions-item label="简介">
              {{ picture.introduction ?? '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="分类">
              {{ picture.category ?? '默认' }}
            </a-descriptions-item>
            <a-descriptions-item label="标签">
              <a-tag v-for="tag in picture.tags" :key="tag">
                {{ tag }}
              </a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="格式">
              {{ picture.picFormat ?? '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="宽度">
              {{ picture.picWidth ?? '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="高度">
              {{ picture.picHeight ?? '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="宽高比">
              {{ picture.picScale ?? '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="主色调">
              <div style="display: flex; align-items: center; gap: 8px">
                <span>{{ picture.picColor ?? '-' }}</span>
                <div
                  v-if="picture.picColor"
                  :style="{
                    backgroundColor: toHexColor(picture.picColor),
                    width: '16px',
                    height: '16px',
                    border: '1px solid #ccc',
                    flexShrink: 0,
                  }"
                ></div>
              </div>
            </a-descriptions-item>
          </a-descriptions>
          <a-space wrap>
            <a-button type="default" v-if="canEdit" @click="doEdit"
              >编辑
              <template #icon>
                <EditOutlined />
              </template>
            </a-button>
            <a-button danger v-if="canEdit" @click="doDelete"
              >删除
              <template #icon>
                <DeleteOutlined />
              </template>
            </a-button>
            <a-button type="primary" @click="doDownload"
              >免费下载
              <template #icon>
                <DownloadOutlined />
              </template>
            </a-button>
            <ShareModel ref="showModelRef" :link="shareLink" />
            <a-button type="primary" ghost @click="doShare(picture, e)"
              >分享
              <template #icon>
                <ShareAltOutlined />
              </template>
            </a-button>
          </a-space>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script lang="ts" setup>
import AccessEnum from '@/access/accessEnum'
import { deletePictureUsingPost, getPictureVoByIdUsingGet } from '@/api/pictureController'
import ShareModel from '@/components/ShareModel.vue'
import router from '@/router'
import { useLoginUserStore } from '@/stores/user'
import { downloadImage } from '@/utils'
import { DeleteOutlined, EditOutlined, ShareAltOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { computed, onMounted, ref } from 'vue'

const loginUserStore = useLoginUserStore()
const picture = ref<API.PictureVO>({ tags: [] })
const props = defineProps<{
  id: string | number
}>()

//是否有编辑权限
const canEdit = computed(() => {
  const loginUser = loginUserStore.loginUser
  //未登录不能编辑
  if (!loginUser) {
    return false
  }
  //仅本人或者管理员可编辑
  const user = picture.value.user || {}
  return loginUser.id === user.id || loginUser.userRole === AccessEnum.ADMIN
})
const showModelRef = ref()
const shareLink = ref('')
//分享
const doShare = (picture: API.PictureVO, e) => {
  if (e) {
    e.stopPropagation()
  }
  shareLink.value = `${window.location.protocol}//${window.location.host}/picture/${picture.id}`
  if (shareLink.value) {
    showModelRef.value.openModal()
  }
}
//获取图片详情
const getPictureDetail = async () => {
  try {
    const res = await getPictureVoByIdUsingGet({
      id: props.id,
    })
    console.log('获取图片详情', res)
    if (res.data.code === 0 && res.data.data) {
      picture.value = res.data.data
    } else {
      message.error(res.data.message)
    }
  } catch (e: any) {
    message.error(e.message)
  }
}
//编辑
const doEdit = async () => {
  router.push('/add_picture?id=' + picture.value.id)
}
//删除
const doDelete = async () => {
  const id = picture.value.id
  if (id === null || id === undefined) {
    message.warning('图片ID不存在，无法删除')
    return
  }
  try {
    const res = await deletePictureUsingPost(id)
    if (res.data.code === 0) {
      message.success('删除成功')
      router.push('/')
    } else {
      message.error(`删除失败：${res.data.message || '未知错误'}`)
    }
  } catch (e: any) {
    message.error(`删除失败：${e.message || '网络异常'}`)
  }
}
//下载
const doDownload = async () => {
  downloadImage(picture.value.url)
}
const toHexColor = (input: string) => {
  if (!input) return '#000000'
  let hex = input.startsWith('0x') ? input.substring(2) : input
  if (hex.length === 3) {
    hex = hex
      .split('')
      .map((c) => c + c)
      .join('')
  }
  hex = hex.padEnd(6, '0')
  return `#${hex}`
}
onMounted(() => {
  getPictureDetail()
})
</script>

<style lang="scss" scoped></style>
